package com.zjmzxfzhl.modules.purchase.service.impl;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zjmzxfzhl.common.base.BaseServiceImpl;
import com.zjmzxfzhl.common.exception.AppException;
import com.zjmzxfzhl.common.util.FileUtil;
import com.zjmzxfzhl.common.util.PathUtil;
import com.zjmzxfzhl.modules.purchase.controller.dto.PurchaseFileQueryDto;
import com.zjmzxfzhl.modules.purchase.controller.vo.PurchaseFileVo;
import com.zjmzxfzhl.modules.purchase.entity.PurchaseFile;
import com.zjmzxfzhl.modules.purchase.mapper.PurchaseFileMapper;
import com.zjmzxfzhl.modules.purchase.service.PurchaseFileService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * Service
 *
 * @author 庄金明
 */
@Service
public class PurchaseFileServiceImpl extends BaseServiceImpl<PurchaseFileMapper, PurchaseFile>
        implements PurchaseFileService {
    @Override
    public IPage<PurchaseFileVo> list(IPage<PurchaseFileVo> page, PurchaseFileQueryDto purchaseFile) {
        return page.setRecords(baseMapper.list(page, purchaseFile));
    }

    @Override
    public void uploadFile(MultipartFile multipartFile, PurchaseFile purchaseFile) {
        String fileOriginalName = multipartFile.getOriginalFilename();
        if (StringUtils.isEmpty(fileOriginalName)) {
            throw new AppException("文件原始名称缺失");
        }
        try {
            File targetFile = PathUtil.getDefaultFile(fileOriginalName);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(targetFile));
            IoUtil.write(stream, true, multipartFile.getBytes());
            String fileSize = FileUtil.getFileSize(targetFile);
            String filePath = targetFile.getName();
            if (FileUtil.isImage(fileOriginalName)) {
                //针对图像缩放  （按比例缩放）
                File scaledFile = FileUtil.scaleFit(targetFile, fileOriginalName, fileSize);
                if (null != scaledFile) {
                    purchaseFile.setScaledFilePath(scaledFile.getName());
                }
            }
            purchaseFile.setFileSize(fileSize);
            purchaseFile.setFileOriginalName(fileOriginalName);
            purchaseFile.setFilePath(filePath);
            purchaseFile.setFileType(StringUtils.getFilenameExtension(fileOriginalName));
            this.save(purchaseFile);
        } catch (Exception ex) {
            throw new AppException("附件上传失败:" + ex.getMessage());
        }
    }

    @Override
    public void deleteFiles(List<Long> fileIds) {
        for (Long fileId : fileIds) {
            PurchaseFile dsFile = this.getById(fileId);
            if (null != dsFile) {
                this.removeById(fileId);
                deleteRealFile(dsFile);
            }
        }
    }

    public void deleteRealFile(PurchaseFile purchaseFile) {
        if (!StringUtils.isEmpty(purchaseFile.getFilePath())) {
            String fileAbsolutePath = PathUtil.getDefaultRootPath(PathUtil.DEFAULT_PATH) + File.separator + purchaseFile.getFilePath();
            cn.hutool.core.io.FileUtil.del(fileAbsolutePath);
        }

        if (!StringUtils.isEmpty(purchaseFile.getScaledFilePath())) {
            String scaledFileAbsolutePath = PathUtil.getDefaultRootPath(PathUtil.DEFAULT_PATH) + File.separator + purchaseFile.getScaledFilePath();
            cn.hutool.core.io.FileUtil.del(scaledFileAbsolutePath);
        }
    }

    /**
     * 阅读文档
     *
     * @param response
     * @param fileId
     */
    @Override
    public void readFile(HttpServletResponse response, Long fileId) {
        PurchaseFile dsFile = this.getById(fileId);
        if (null != dsFile && !StringUtils.isEmpty(dsFile.getFilePath())) {
            //存在缩略图则查看缩略图
            String realPath = dsFile.getScaledFilePath();
            if (StringUtils.isEmpty(realPath)) {
                realPath = dsFile.getFilePath();
            }
            String fileAbsolutePath = PathUtil.getDefaultRootPath(PathUtil.DEFAULT_PATH) + File.separator + realPath;
            File file = new File(fileAbsolutePath);
            if (file.exists()) {
                FileUtil.setPreviewResponse(response, file, dsFile.getFileOriginalName());
            } else {
                throw new AppException("磁盘文件不存在");
            }
        } else {
            throw new AppException("文件可能已删除，无法获取文件路径");
        }
    }


    /**
     * 下载文档
     *
     * @param response
     * @param fileId
     */
    @Override
    public void downloadFile(HttpServletResponse response, Long fileId) {
        PurchaseFile dsFile = this.getById(fileId);
        if (null != dsFile && !StringUtils.isEmpty(dsFile.getFilePath())) {
            String fileAbsolutePath = PathUtil.getDefaultRootPath(PathUtil.DEFAULT_PATH) + File.separator + dsFile.getFilePath();
            File file = new File(fileAbsolutePath);
            if (file.exists()) {
                FileUtil.setDownloadResponse(response, file, dsFile.getFileOriginalName());
            } else {
                throw new AppException("磁盘文件不存在");
            }
        } else {
            throw new AppException("文件可能已删除，无法获取文件路径");
        }
    }


}
